package com.sgb.alimaplibrary;

import android.app.ProgressDialog;
import android.content.Context;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sgb.alimaplibrary.entity.PoiOverlay;
import com.sgb.alimaplibrary.util.AMapUtil;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.swgk.core.util.MToast;

import java.util.List;

/**
 * poi热点搜索
 */
public class MapPoiTools implements PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener {

    private final AMap mAMap;
    private final GeocodeSearch geocoderSearch;
    private Context mContext;
    private ProgressDialog progDialog = null;// 搜索时进度条
    private PoiSearch poiSearch;
    private PoiSearch.Query query;
    private int currentPage = 0;// 当前页面，从0开始计数

    public CalllBack mCallBack;
    private PoiResult poiResult;
    private String mKeyWord = "";
    private PoiOverlay poiOverlay;
    private LatLonPoint latLonPoint;
    private String cityName = "";

    public abstract static class CalllBack {
        public void showSuggestCity(List<SuggestionCity> suggestionCityList, List<PoiItem> poiItems, int currentPage) {
        }

        public void onRegeocodeSearched(String suggestionCityList) {
        }

        public void onRegeocodeSearched(GeocodeAddress address) {
        }
    }

    public static MapPoiTools newInstance(Context mContext, AMap mAMap, CalllBack mCallBack) {
        return new MapPoiTools(mContext, mAMap, mCallBack);
    }

    public MapPoiTools(Context mContext, AMap mAMap, CalllBack mCallBack) {
        this.mContext = mContext;
        this.mCallBack = mCallBack;
        this.mAMap = mAMap;
        geocoderSearch = new GeocodeSearch(mContext);
        geocoderSearch.setOnGeocodeSearchListener(this);
    }

    public void doSearchQuery(String keyWord, String cityName) {
        if ("".equals(keyWord) && "".equals(cityName)) {
            MToast.showLongToast(mContext, "请输入搜索关键字");
            return;
        } else {
            currentPage = 0;
            poiResult = null;
            mKeyWord = keyWord;
            poiSearchQuery(keyWord, cityName);
        }
    }


    public void addressSearchQuery(String addreaa, String cityName) {
        if ("".equals(addreaa)) {
            MToast.showLongToast(mContext, "地址信息不正确");
            return;
        } else {
            // name表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode
            GeocodeQuery query = new GeocodeQuery(addreaa, cityName);
            geocoderSearch.getFromLocationNameAsyn(query);
        }
    }


    public void latlotSearchQuery(LatLng latLng) {
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }


    public PoiSearch.Query setQuery(String keyWord, String cityName, int count) {
        query = new PoiSearch.Query(keyWord, "", cityName);
        query.setPageSize(count);// 设置每页最多返回多少条poiitem
        return query;
    }

    public void poiSearchQuery(String keyWord, String cityName) {
        query = new PoiSearch.Query(keyWord, "", cityName);
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查寻页数
        poiSearch = new PoiSearch(mContext, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    /**
     * 点击下一页按钮
     */
    public void nextButton() {
        if (query != null && poiSearch != null && poiResult != null) {
            if (poiResult.getPageCount() - 1 > currentPage) {
                currentPage++;
                query.setPageNum(currentPage);// 设置查后一页
                poiSearch.searchPOIAsyn();
            } else {
                MToast.showLongToast(mContext,
                        mContext.getResources().getString(R.string.no_result));
            }
        }
    }

    /**
     * POI信息查询回调方法
     */
    @Override
    public void onPoiSearched(PoiResult poiResult, int rCode) {
        dissmissProgressDialog();// 隐藏对话框
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getQuery() != null) {// 搜索poi的结果
                if (poiResult.getQuery().equals(query)) {// 是否是同一条
                    this.poiResult = poiResult;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {
                        if (mCallBack != null) {
                            mCallBack.showSuggestCity(suggestionCities, poiItems, currentPage);
                        }
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        if (mCallBack != null) {
                            mCallBack.showSuggestCity(suggestionCities, poiItems, currentPage);
                        }
                    } else {
                        MToast.showLongToast(mContext,
                                mContext.getResources().getString(R.string.no_result));
                    }
                }
            } else {
                MToast.showLongToast(mContext,
                        mContext.getResources().getString(R.string.no_result));
            }
        } else {
            ToastUtil.showerror(mContext, rCode);
        }
    }

    public void resetOtherMarker(List<PoiItem> poiItems) {
        if (poiItems != null && poiItems.size() > 0) {
            mAMap.clear();// 清理之前的图标
            poiOverlay = new PoiOverlay(mContext, mAMap, poiItems);
            poiOverlay.removeFromMap();
            poiOverlay.addToMap(0, true);
            poiOverlay.zoomToSpan();
        }
    }

    public void setMarkerIcon(int index, boolean isShowText) {
        if (poiOverlay != null) {
            poiOverlay.getBitmapDescriptor(true, index, 0, isShowText);

            mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(poiOverlay.getPoiItem(index).getLatLonPoint().getLatitude(),
                    poiOverlay.getPoiItem(index).getLatLonPoint().getLongitude()), 12f));
        }
    }

    //根据中心点和自定义内容获取缩放bounds
    private LatLngBounds getLatLngBounds(LatLng centerpoint, List<LatLng> pointList) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (centerpoint != null) {
            for (int i = 0; i < pointList.size(); i++) {
                LatLng p = pointList.get(i);
                LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
                b.include(p);
                b.include(p1);
            }
        }
        return b.build();
    }

    /**
     * 获取PoiItem获取POI的详细信息
     *
     * @param poiItem
     * @param rCode
     */
    @Override
    public void onPoiItemSearched(PoiItem poiItem, int rCode) {
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(mContext);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在搜索:\n" + mKeyWord);
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }


    /**
     * 通过经纬度获取地址
     *
     * @param regeocodeResult
     * @param rCode
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (regeocodeResult != null && regeocodeResult.getRegeocodeAddress() != null
                    && regeocodeResult.getRegeocodeAddress().getFormatAddress() != null) {
                String addressName = regeocodeResult.getRegeocodeAddress().getFormatAddress();
                mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        AMapUtil.convertToLatLng(latLonPoint), 15));
                cityName = regeocodeResult.getRegeocodeAddress().getCity();
                if (mCallBack != null) {
                    mCallBack.onRegeocodeSearched(addressName);
                }
            } else {
                ToastUtil.show(mContext, R.string.no_result);
            }
        } else {
            ToastUtil.showerror(mContext, rCode);
        }
    }

    public String getCityName() {
        return cityName;
    }

    /**
     * 通过地址获取经纬度
     *
     * @param geocodeResult
     * @param rCode
     */
    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null
                    && geocodeResult.getGeocodeAddressList().size() > 0) {
                GeocodeAddress address = geocodeResult.getGeocodeAddressList().get(0);
                if (mAMap != null) {
                    mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                            AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
                }
//                addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
//                        + address.getFormatAddress();
                if (mCallBack != null) {
                    mCallBack.onRegeocodeSearched(address.getFormatAddress());
                    mCallBack.onRegeocodeSearched(address);
                }
            } else {
                ToastUtil.show(mContext, R.string.no_result);
            }
        } else {
            ToastUtil.showerror(mContext, rCode);
        }
    }

}
